<template>
  <div class="dashboard-editor-container">
    <div class="trainTask">
      <div class="topSearch">
        <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset" />
        <div class="tabclick">
          <div class="tabitem" @click="handleClick()">
            <span><i :class="tab ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
          </div>
        </div>
        <el-row>
          <el-tabs type="border-card" v-if="tab" style="margin-top: 16px" @tab-click="tabClick">
            <el-tab-pane label="日期趋势" lazy>
              <el-col :xs="24" :sm="24" :lg="24">
                <task-train-chart title="日期趋势" :chart-data="barchartData" @barClick="echartsClick" />
              </el-col>
            </el-tab-pane>
          </el-tabs>
        </el-row>
      </div>
      <div class="bottomDisplay">
        <el-table stripe :data="tableData" style="width: 100%; margin-top: 15px">
          <el-table-column
            label="序号"
            width="60px"
            type="index"
            :index="
              (index) => {
                return index + 1 + (this.pageNum - 1) * this.pageSize;
              }
            "
          >
          </el-table-column>
          <el-table-column
            label="文件名称"
            prop="FileRawName"
            align="left"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column label="文件类型" prop="FileType" align="left"  width="180" show-overflow-tooltip></el-table-column>
          <el-table-column label="任务状态" prop="TaskStatus" width="180" show-overflow-tooltip>
            <template slot-scope="{ row }">
              <span :style="{ color: taskStatus[row.TaskStatus] && taskStatus[row.TaskStatus].color }">
                {{ (taskStatus[row.TaskStatus] && taskStatus[row.TaskStatus].text) || "未知" }}</span
              >
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="CreateTime" width="180" show-overflow-tooltip>
            <template slot-scope="{ row }">
              <span>{{ parseTime(row.CreateTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态最后更新时间" prop="StatusUpdateTime" width="180" show-overflow-tooltip>
            <template slot-scope="{ row }">
              <span>{{ parseTime(row.StatusUpdateTime) }}</span>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-size="pageSize"
          background
          layout="total, prev, pager, sizes, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import connsearch from "@/components/connSearch";
import { parseTime } from "@/utils/index.js";
import { Task_URLS } from "./api/request";
import { noTokenRequest } from "@/api/material";
import Cookies from "js-cookie";
import TaskTrainChart from "@/views/Material/components/TaskTrainChart.vue";
import { directRequest } from "@/api/firstPage";
export default {
  name: "trainTask",
  components: {
    TaskTrainChart,
    connsearch
  },
  created() {
    this.pageSize = Cookies.get("DefaultPageLength") * 1;
    let endTime = new Date(new Date().setHours(0, 0, 0, 0));
    let startTime = endTime - Cookies.get("DefaultLogDays") * 1 * 3600 * 24 * 1000;
    // let arr = [ parseTime(startTime), parseTime(xTime)]
    let arr = [parseTime(startTime), ""];
    this.formOptions.map((item) => {
      if (item.label === "创建时间") {
        item.initValue = arr;
      }
    });
    this.$set(this.searchform, "timeRange", arr);

    if (this.checkHasIP()) {
      this.getData();
    }
  },
  data() {
    let that = this;
    return {
      tab: false,
      barchartData: {},
      formOptions: [
        {
          col: 8,
          label: "创建时间",
          prop: "timeRange",
          element: "el-date-picker",
          initValue: [],
          type: "",
          events: {
            input(val) {
              that.searchform.timeRange = val;
            }
          }
        },
        {
          col: 5,
          label: "文件类型",
          prop: "FileType",
          element: "el-select",
          initValue: "",
          placeholder: "请选择文件类型",
          options: [
            { label: "全部", value: "" },
            { label: "docx", value: ".docx" },
            { label: "doc", value: ".doc" },
            { label: "pdf", value: ".pdf" },
            { label: "ppt", value: ".ppt" },
            { label: "pptx", value: ".pptx" }
          ],
          events: {
            input(val) {
              that.searchform.FileType = val;
            }
          }
        },
        {
          col: 5,
          label: "任务状态",
          prop: "TaskStatus",
          element: "el-select",
          initValue: 0,
          placeholder: "请选择任务状态",
          options: [
            { label: "全部", value: 0 },
            { label: "待执行", value: 1 },
            { label: "执行中", value: 2 },
            { label: "成功", value: 3 },
            { label: "失败", value: 4 },
            { label: "任务删除", value: 5 },
            { label: "失败，准备重试", value: 6 }
          ],
          events: {
            input(val) {
              that.searchform.TaskStatus = val;
            }
          }
        }
      ],
      taskStatus: {
        1: { text: "待执行", color: "#E6A23C" },
        2: { text: "执行中", color: "#409EFF" },
        3: { text: "成功", color: "#67C23A" },
        4: { text: "失败", color: "#F56C6C" },
        5: { text: "任务删除", color: "#909399" },
        6: { text: "失败，准备重试", color: "#F56C6C" }
      },
      knowledgeIP: "",
      searchform: {},
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      total: 0
    };
  },
  methods: {
    parseTime,
    async getData() {
      await this.getTrainTasks();
    },
    checkHasIP() {
      this.knowledgeIP = localStorage.getItem("KnowledgeIP");
      if (this.knowledgeIP) {
        return true;
      } else {
        this.$message.error("请先配置知识库地址");
        return false;
      }
    },
    async getTrainTasks() {
      const data = {
        FileType: this.searchform.FileType,
        TaskStatus: this.searchform.TaskStatus || 0,
        StartCreateTime: this.searchform.timeRange?.[0] || "",
        EndCreateTime: this.searchform.timeRange?.[1] || "",
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        }
      };
      const res = await noTokenRequest(Task_URLS.getTask, data);
      if (res.Status.StatusCode === 0) {
        this.tableData = res.Data;
        this.total = res.Paging.TotalCount;
      }
    },
    handleSizeChange(val) {
      this.pageNum = 1;
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.getData();
    },
    search(val) {
      this.pageNum = 1;
      this.searchform = { ...val };
      if (this.searchform.timeRange) {
        this.searchobj = {
          StartCreateTime: this.searchform?.timeRange[0] || "",
          EndCreateTime: this.searchform?.timeRange[1] || ""
        };
      }
      this.getData();
    },
    reset() {
      let endTime = new Date(new Date().setHours(0, 0, 0, 0));
      let startTime = endTime - Cookies.get("DefaultLogDays") * 1 * 3600 * 24 * 1000;
      let arr = [parseTime(startTime), ""];
      this.pageNum = 1;
      this.formOptions = this.formOptions.map((item) => {
        if (item.label === "创建时间") {
          item.initValue = arr;
        } else if (item.label === "请选择文件类型") {
          item.initValue = "";
        } else if (item.label === "任务状态") {
          item.initValue = 0;
        }
        return item;
      });
      this.searchform = {};
      this.$set(this.searchform, "timeRange", arr);
      this.$refs.connsearch.addInitValue();
      this.getData();
    },
    handleClick() {
      this.tab = !this.tab;
      this.getVectaskSumGroupbyDate();
    },
    echartsClick(val, title) {
      this.pageNum = 1;
      if (title === "日期趋势") {
        this.searchobj = { ...this.searchobj, timeRange: [`${val} 00:00:00`, `${val} 23:59:59`] };
        this.search(this.searchobj);
      }
    },
    tabClick(row) {
      this.tabTitle = row.label;
      switch (this.tabTitle) {
        case "日期趋势":
          this.getVectaskSumGroupbyDate();
          break;
        default:
          this.getVectaskSumGroupbyDate();
          break;
      }
    },
    async getVectaskSumGroupbyDate() {
      const res = await directRequest("/zyq/get_vectask_sum_groupby_date", {});
      if (res.Status.StatusCode === 0) {
        let xAxis = [];
        let failSum = [];
        let successSum = [];
        let pendingExecution = [];
        let inProgress = [];
        let taskDeletion = [];
        let retry = [];
        if (res.Data) {
          res.Data.forEach((item) => {
            xAxis.push(item.TransDate);
            failSum.push(item.FailSum);
            successSum.push(item.SuccessSum);
            pendingExecution.push(item.WaitExeSum)
            inProgress.push(item.ExeSum)
            taskDeletion.push(item.DelSum)
            retry.push(item.WaitReSum)
          });
        }
        this.barchartData = {
          xAxis,
          failSum,
          successSum,
          pendingExecution,
          inProgress,
          taskDeletion,
          retry
        };
      } else {
        this.$message.error(res.Status.StatusMsg);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.trainTask {
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  padding: 20px;
  background: #fff;
}
.night {
  .trainTask {
    background: #303445;
  }
}
</style>
